package br.gov.cemaden.cliente.cptec.metar;

import br.gov.cemaden.library.repository.alerta.AerodromoRepository;
import br.gov.cemaden.library.model.alerta.Aerodromo;
import br.gov.cemaden.library.model.alerta.Agencia;
import br.gov.cemaden.library.model.observacao.Metar;
import br.gov.cemaden.library.repository.alerta.AgenciaRepository;
import br.gov.cemaden.library.repository.observacao.MetarRepository;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.Queue;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;

/**
 * 
 *
 */
public class ClienteMetar 
{
    public static void main( String[] args )
    {
        
        Logger logger = LoggerFactory.getLogger(ClienteMetar.class);
        Marker FATAL = MarkerFactory.getMarker("FINAL");
        
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("cliente-cptec-metar");
        EntityManager em = emf.createEntityManager();        
        
        String address = "http://servicos.cptec.inpe.br/XML/estacao/<?>/condicoesAtuais.xml";
        
        AgenciaRepository agencias = new AgenciaRepository(em);
        Agencia agencia = agencias.find("CPTEC");
        if(agencia == null){
            logger.error(FATAL, "There is none agency called CPTEC on the database");
            throw new RuntimeException("There is none agency called CPTEC on the database");
        }
        
        AerodromoRepository repository = new AerodromoRepository(em);        
        
        Queue<Aerodromo> aerodromos = new LinkedList<Aerodromo>();
        aerodromos.addAll(repository.list());        
        
        while(!aerodromos.isEmpty()){

            Aerodromo aerodromo = aerodromos.remove();
            
            URL url = null;
            
            try {
                url = new URL(address.replace("<?>", aerodromo.getSigla()));
                InputStream stream = url.openStream();
                
                XMLReader reader = new XMLReader(stream);
                
                Metar m = reader.getMetar();     
                
                m.setAerodromo(aerodromo);
                m.setAgencia(agencia);
                
                MetarRepository repo = new MetarRepository(em);
                
                if(repo.find(m.getAtualizacao(), aerodromo) == null){                
                    repo.persist(m);
                }
                
                System.out.printf("Aerodromo %s - %s atualizado em %s%n%n", aerodromo.getNome(), 
                        aerodromo.getSigla(), 
                        new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(m.getAtualizacao()));
                
            } catch (MalformedURLException ex) {                
                logger.error(String.format("Error when trying to read url %s", url.toString()), ex);
                //aerodromos.add(aerodromo);
            }
            catch (IOException ex) {
                logger.error(String.format("Error when trying to open file %s", url.toString()), ex);
                //aerodromos.add(aerodromo);
            }            
        }        
    }
}
